package com.jiawa.train.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.train.business.domain.DailyTrainStation;
import com.jiawa.train.business.domain.DailyTrainStationExample;
import com.jiawa.train.business.domain.Train;
import com.jiawa.train.business.domain.TrainStation;
import com.jiawa.train.business.mapper.DailyTrainStationMapper;
import com.jiawa.train.business.req.DailyTrainStationQueryReq;
import com.jiawa.train.business.req.DailyTrainStationSaveReq;
import com.jiawa.train.business.resp.DailyTrainStationQueryResp;
import com.jiawa.train.business.service.DailyTrainStationService;
import com.jiawa.train.business.service.TrainStationService;
import com.jiawa.train.common.exception.BusinessException;
import com.jiawa.train.common.exception.BusinessExceptionEnum;
import com.jiawa.train.common.resp.PageResp;
import com.jiawa.train.common.util.SnowUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author zzl
 * @version 1.0
 */
@Service
public class DailyTrainStationServiceImpl implements DailyTrainStationService {
    private static final Logger LOG = LoggerFactory.getLogger(DailyTrainStationServiceImpl.class);
    
    @Resource
    private DailyTrainStationMapper dailyTrainStationMapper;
    @Resource
    private TrainStationService trainStationService;
    
    @Override
    public void save(DailyTrainStationSaveReq req) {
        DateTime now = DateTime.now();
        DailyTrainStation dailyTrainStation = BeanUtil.copyProperties(req, DailyTrainStation.class);
        if(ObjectUtil.isNull(dailyTrainStation.getId())) {
            if(isExist(dailyTrainStation)) {
                throw new BusinessException(BusinessExceptionEnum.TRAIN_STATION_IS_EXIST);
            } else {
                dailyTrainStation.setId(SnowUtil.getSnowflakeNextId());
                dailyTrainStation.setCreateTime(now);
                dailyTrainStation.setUpdateTime(now);
                dailyTrainStationMapper.insert(dailyTrainStation);
            }
        } else {
            dailyTrainStation.setUpdateTime(now);
            dailyTrainStationMapper.updateByPrimaryKeySelective(dailyTrainStation);
        }
    }

    /**
     * 分页查询每日高铁经停站数据
     * @param req
     * @return
     */
    @Override
    public PageResp<DailyTrainStationQueryResp> queryList(DailyTrainStationQueryReq req) {
        DailyTrainStationExample dailyTrainStationExample = new DailyTrainStationExample();
        dailyTrainStationExample.setOrderByClause("date asc, train_code asc");
        DailyTrainStationExample.Criteria criteria = dailyTrainStationExample.createCriteria();
        if(ObjectUtil.isNotNull(req.getDate())) {
            criteria.andDateEqualTo(req.getDate());
        }
        if(ObjectUtil.isNotNull(req.getTrainCode())) {
            criteria.andTrainCodeEqualTo(req.getTrainCode());
        }

        LOG.info("查询页码：{}", req.getPage());
        LOG.info("每页条数：{}", req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<DailyTrainStation> dailyTrainStationList = dailyTrainStationMapper.selectByExample(dailyTrainStationExample);

        PageInfo<DailyTrainStation> pageInfo = new PageInfo<>(dailyTrainStationList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<DailyTrainStationQueryResp> dailyTrainStationQueryRespList = BeanUtil.copyToList(dailyTrainStationList, DailyTrainStationQueryResp.class);

        PageResp<DailyTrainStationQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(dailyTrainStationQueryRespList);

        return pageResp;
    }

    @Override
    public void delete(Long id) {
        dailyTrainStationMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据日期和高铁车次生成每日高铁经停站数据
     * @param date
     * @param train
     */
    @Transactional
    @Override
    public void genDailyTrainStation(Date date, Train train) {
        LOG.info("生成日期【{}】车次【{}】的车站信息开始", DateUtil.formatDate(date), train.getCode());
        DailyTrainStationExample dailyTrainStationExample = new DailyTrainStationExample();
        dailyTrainStationExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(train.getCode());
        // 1.删除指定日期高铁经停站数据
        dailyTrainStationMapper.deleteByExample(dailyTrainStationExample);

        // 2.查询指定日期高铁经停站，判断是否为空
        List<TrainStation> trainStationList = trainStationService.selectByTrainCode(train.getCode());
        if(CollUtil.isEmpty(trainStationList)) {
            LOG.info("火车车站基础数据为空");
            return;
        }

        // 3.遍历每日高铁经停站数据并插入
        DateTime now = DateTime.now();
        for(TrainStation trainStation : trainStationList) {
            DailyTrainStation dailyTrainStation = BeanUtil.copyProperties(trainStation, DailyTrainStation.class);
            dailyTrainStation.setId(SnowUtil.getSnowflakeNextId());
            dailyTrainStation.setDate(date);
            dailyTrainStation.setCreateTime(now);
            dailyTrainStation.setUpdateTime(now);
            dailyTrainStationMapper.insert(dailyTrainStation);
        }
        LOG.info("生成日期【{}】车次【{}】的车站信息结束", DateUtil.formatDate(date), train.getCode());
    }

    /**
     * 根据日期和高铁车次查询每日高铁经停站数据
     * @param date
     * @param code
     * @return
     */
    @Override
    public List<DailyTrainStation> selectByDateAndTrainCode(Date date, String code) {
        DailyTrainStationExample dailyTrainStationExample = new DailyTrainStationExample();
        dailyTrainStationExample.setOrderByClause("`index` asc");
        dailyTrainStationExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(code);

        return dailyTrainStationMapper.selectByExample(dailyTrainStationExample);
    }

    /**
     * 根据日期和高铁车次，统计每日高铁经停站数
     * @param date
     * @param trainCode
     * @return
     */
    @Override
    public long countByTrainCode(Date date, String trainCode) {
        DailyTrainStationExample dailyTrainStationExample = new DailyTrainStationExample();
        dailyTrainStationExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode);
        return dailyTrainStationMapper.countByExample(dailyTrainStationExample);
    }

    /**
     * 判断每日高铁经停站是否存在
     * @param dailyTrainStation
     * @return
     */
    private boolean isExist(DailyTrainStation dailyTrainStation) {
        DailyTrainStationExample dailyTrainStationExample = new DailyTrainStationExample();
        dailyTrainStationExample.createCriteria()
                .andDateEqualTo(dailyTrainStation.getDate())
                .andTrainCodeEqualTo(dailyTrainStation.getTrainCode());
        List<DailyTrainStation> list = dailyTrainStationMapper.selectByExample(dailyTrainStationExample);
        if(CollUtil.isNotEmpty(list)) return true;
        else return false;
    }
}
